<!DOCTYPE html>
<!--<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">-->
<head>
    <meta charset="UTF-8">
    <title>内网穿透</title>
</head>

<!--<script src="./js/jquery-3.5.1.js"></script>-->
<!--<link rel="stylesheet" href="./css/bootstrap.min.css">-->
<!--<script src="./js/bootstrap.bundle.min.js"></script>-->

<script th:src="@{/js/jquery-3.5.1.js}"></script>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<script th:src="@{/js/bootstrap.bundle.min.js}"></script>

<!--<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">-->
<!--<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>-->
<body>
<div class="fixed-top">
    <div class="collapse" id="navbarToggleExternalContent">
        <div class="bg-dark p-4">
            <h5 class="text-white h4">Collapsed content</h5>
            <span class="text-muted">Toggleable via the navbar brand.</span>
        </div>
    </div>
    <nav class="navbar navbar-dark bg-dark">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent"
                aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
    </nav>
</div>
<div style="height: 56px"></div>

<div class="overflow-hidden" style="margin-right: 5px">
    <button type="button" class="btn btn-primary float-right" style="margin: 5px 0 5px 5px" onclick="add()">
        添加
    </button>

    <a th:href="@{/download-client}">
        <button type="button" class="btn btn-primary float-right" style="margin: 5px 0 5px 5px">
            下载客户端
        </button>
    </a>
</div>

<table class="table  table-hover">
    <caption>基本的表格布局</caption>
    <thead>
    <tr>
        <th>共<span th:text="${clients.size()}"></span>个</th>
        <th>key</th>
        <th>备注</th>
        <th>创建时间</th>
        <th th:text="'在线:'+${onLineCount}"></th>
        <th>条数</th>
        <th style="width: 145px;text-align: right">操作</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="client,clientStat : ${clients}">
        <td th:text="${clientStat.count}"></td>
        <td th:text="${client.getKey()}"></td>
        <td th:text="${client.getRemark()}"></td>
        <td th:text="${client.getCreateTime()}"></td>
        <td>
            <div class="dropdown">
                <button th:if="${client.isOnline()}" class="btn btn-success dropdown-toggle" type="button"
                        data-toggle="dropdown"
                        aria-expanded="false">
                    在线
                </button>
                <button th:unless="${client.isOnline()}" class="btn btn-secondary dropdown-toggle" type="button"
                        data-toggle="dropdown"
                        aria-expanded="false">
                    离线
                </button>
                <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
                    <button class="dropdown-item" type="button" th:key="${client.getKey()}"
                            onclick="disconnect(this.getAttribute('key'))">断开连接
                    </button>
                    <button class="dropdown-item" type="button" th:key="${client.getKey()}"
                            onclick="forcedDisconnect(this.getAttribute('key'))">强制断开连接
                    </button>
                </div>
            </div>
        </td>
        <td>

            <div class="dropdown">
                <button class="btn badge-primary badge-pill dropdown-toggle" type="button"
                        data-toggle="dropdown" th:text="${client.getForwards().size()}"
                        aria-expanded="false">
                </button>
                <div class="dropdown-menu" aria-labelledby="dropdownMenu2">
                    <button class="dropdown-item" type="button"
                            th:each="forward,forwardStat : ${client.getForwards()}"
                            th:text="${forward.getServerport()}+' -> '+${forward.getLocalhost()}+':'+${forward.getLocalport()}"></button>
                </div>
            </div>
        </td>
        <td>
            <button type="button" class="btn btn-primary" th:key="${client.getKey()}"
                    onclick="edit(this.getAttribute('key'))">编辑
            </button>
            <button type="button" class="btn btn-danger" th:key="${client.getKey()}"
                    onclick="del(this.getAttribute('key'))">删除
            </button>
        </td>
    </tr>
    </tbody>
</table>

<!-- Add Modal -->
<div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addModalLabel">添加</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="forwardKey">key:</label>
                </div>
                <div class="input-group mb-3">
                    <input type="text" class="form-control" placeholder="Recipient's username" id="addForwardKey"
                           aria-label="Recipient's username" aria-describedby="button-addon">
                    <div class="input-group-append">
                        <button class="btn btn-outline-secondary" type="button" id="button-addon"
                                onclick="$('#addForwardKey').val(ranStr());">随机
                        </button>
                    </div>
                </div>
                <ul class="list-group" id="addForwardGroup">
                    <li class="list-group-item">An item</li>
                    <li class="list-group-item">A second item</li>
                    <li class="list-group-item">A third item</li>
                    <li class="list-group-item">A fourth item</li>
                    <li class="list-group-item">
                        And a fifth one
                        <button type="button" class="btn btn-danger float-right">
                            删除
                        </button>
                    </li>
                </ul>
                <div class="form-group">
                    <label for="forWardInput">添加映射:（请以 [服务器端口] : [本地主机地址] : [本地主机端口] 形式输入 例
                        8022:127.0.0.1:22）</label>
                    <input type="text" class="form-control" id="addForWardInput"
                           placeholder="请输入 -> ">
                </div>
                <button type="button" class="btn btn-primary" onclick="addForWardAdd()">添加</button>
                <div class="form-group">
                    <label for="addRemark">备注:</label>
                    <input type="text" class="form-control" id="addRemark">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="insert()">添加</button>
            </div>
        </div>
    </div>
</div>


<!-- Update Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateModalLabel">修改</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="forwardKey">key:</label>
                        <input type="text" class="form-control" id="forwardKey" placeholder="key" readonly>
                    </div>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" placeholder="Recipient's username"
                               aria-label="Recipient's username" aria-describedby="button-addon2">
                        <div class="input-group-append">
                            <button class="btn btn-outline-secondary" type="button" id="button-addon2">Button</button>
                        </div>
                    </div>
                    <ul class="list-group" id="forwardGroup">
                        <li class="list-group-item">An item</li>
                        <li class="list-group-item">A second item</li>
                        <li class="list-group-item">A third item</li>
                        <li class="list-group-item">A fourth item</li>
                        <li class="list-group-item">
                            And a fifth one
                            <button type="button" class="btn btn-danger float-right">
                                删除
                            </button>
                        </li>
                    </ul>
                    <div class="form-group">
                        <label for="forWardInput">添加映射:（请以 [服务器端口] : [本地主机地址] : [本地主机端口] 形式输入 例
                            8022:127.0.0.1:22）</label>
                        <input type="text" class="form-control" id="forWardInput"
                               placeholder="请输入 -> ">
                    </div>
                    <button type="button" class="btn btn-primary" onclick="updateForWardAdd()">添加</button>
                    <div class="form-group">
                        <label for="updateRemark">备注:</label>
                        <input type="text" class="form-control" id="updateRemark">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="update()">保存</button>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    function add() {
        $("#addForwardKey").val(ranStr());
        $("#addForwardGroup").empty()
        $("#addRemark").val('')
        $('#addForWardInput').val('')
        $('#addModal').modal('show')
    }

    function addForWardAdd(text) {
        const span = $('<span class="forward"></span>')
        if (text == null) {
            span.html($('#addForWardInput').val())
        } else {
            span.html(text)
        }
        const bt = $('<button type="button" class="btn btn-danger float-right" onclick="forWardRemove(this)">删除</button>')
        const li = $('<li class="list-group-item"></li>')
        li.append(span)
        li.append(bt)
        $("#addForwardGroup").append(li)
    }

    function insert() {
        const span = $("#addForwardGroup .forward")
        let forwards = ''
        console.log(span)
        for (let i = 0; i < span.length; i++) {
            forwards += span[i].innerHTML + ','
        }
        console.log(forwards)
        $.ajax({
            url: "/insert",
            type: "post",
            data: {
                key: $("#addForwardKey").val(),
                remark: $("#addRemark").val(),
                forwards
            },
            success: res => {
                if (res.code === 1) {
                    $('#addModal').modal('hide')
                    location.reload()
                } else {
                    alert(res.msg)
                }
            }
        })
    }


    function edit(key) {
        console.log(key)
        $.ajax({
            url: "/get",
            type: "post",
            data: {
                key
            },
            success: res => {
                console.log(res)
                if (res.code === 1) {
                    $("#forwardKey").val(res.data.key);
                    $("#forwardGroup").empty()
                    $("#updateRemark").val(res.data.remark)
                    $('#forWardInput').val('')
                    for (let i = 0; i < res.data.forwards.length; i++) {
                        updateForWardAdd(res.data.forwards[i].serverport + ":" + res.data.forwards[i].localhost + ":" + res.data.forwards[i].localport);
                    }
                }
            }
        })
        $('#updateModal').modal('show')
    }

    function updateForWardAdd(text) {
        const span = $('<span class="forward"></span>')
        if (text == null) {
            span.html($('#forWardInput').val())
        } else {
            span.html(text)
        }
        const bt = $('<button type="button" class="btn btn-danger float-right" onclick="forWardRemove(this)">删除</button>')
        const li = $('<li class="list-group-item"></li>')
        li.append(span)
        li.append(bt)
        $("#forwardGroup").append(li)
    }

    function forWardRemove(i) {
        i.parentNode.remove()
    }

    function update() {
        const span = $("#forwardGroup .forward")
        let forwards = ''
        console.log(span)
        for (let i = 0; i < span.length; i++) {
            forwards += span[i].innerHTML + ','
        }
        console.log(forwards)
        $.ajax({
            url: "/update",
            type: "post",
            data: {
                key: $("#forwardKey").val(),
                remark: $("#updateRemark").val(),
                forwards
            },
            success: res => {
                if (res.code === 1) {
                    $('#updateModal').modal('hide')
                    location.reload()
                } else {
                    alert(res.msg)
                }
            }
        })
    }

    function disconnect(key) {
        const s = prompt("请输入下一次重连时间（单位秒，输入负数则关闭程序）", 30)
        if (s) {
            $.ajax({
                url: "/disconnect",
                type: "post",
                data: {
                    key,
                    s
                },
                success: res => {
                    if (res.code === 1) {
                        location.reload()

                    } else {
                        alert(res.msg)
                    }
                }
            })
        }
    }

    function forcedDisconnect(key) {
        const b = confirm("要强制关闭客户端的连接吗 客户端将会在30秒之后重新连接")
        if (b) {
            $.ajax({
                url: "/forcedDisconnect",
                type: "post",
                data: {
                    key
                },
                success: res => {
                    if (res.code === 1) {
                        location.reload()
                    } else {
                        alert(res.msg)
                    }
                }
            })
        }
    }

    function del(key) {
        const b = confirm("确定删除吗")
        if (b) {
            $.ajax({
                url: "/delete",
                type: "post",
                data: {
                    key
                },
                success: res => {
                    if (res.code === 1) {
                        location.reload()
                    } else {
                        alert(res.msg)
                    }
                }
            })
        }
    }

    function ranStr(len) {
        len = len || 20;
        var $chars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM01234567890123456789';
        var maxPos = $chars.length;
        var pwd = '';
        for (let i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }
</script>
</html>